import 'package:flutter/material.dart';

/// 动画绘制仿真器
class AnimateSimulator extends StatefulWidget {
  const AnimateSimulator({super.key});

  @override
  AnimateSimulatorState createState() => AnimateSimulatorState();
}

class AnimateSimulatorState extends State<AnimateSimulator>
    with SingleTickerProviderStateMixin {
  /// 定义动画的容差，用来更好的决定动画何时被认为是完成的。这对于精细控制动画的终止条件非常有用，尤其是在物理仿真中
  late final Tolerance _kDefaultTolerance = Tolerance(
    velocity: 1.0 / (0.050 * View.of(context).devicePixelRatio),
    // logical pixels per second
    distance: 1.0 / View.of(context).devicePixelRatio, // logical pixels
  );

  /// 创建一个没有边界的控制器
  late AnimationController animationCtrl =
      AnimationController.unbounded(vsync: this)..addListener(onAnimated);

  void onAnimated() {
    print(animationCtrl.value);
  }

  void _startAnim() async {
    /// 定义 滚动 clamping simulation
    final Simulation simulation = ClampingScrollSimulation(
      /// 初始位置
      position: 100,

      /// 初始速度
      velocity: 1000,

      /// 摩擦力
      friction: 0.015,
      tolerance: _kDefaultTolerance,
    );
    await animationCtrl.animateWith(simulation);
  }

  @override
  void dispose() {
    animationCtrl.removeListener(onAnimated);
    animationCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('模板'),
        ),
        body: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                _startAnim();
              },
              child: Text("开启动画仿真器"),
            ),
          ],
        ));
  }
}
